#	Copyright (C) 2008 Sambit Bikas Pal, IISERK
#	Author: Sambit Bikas Pal , Email: sam@botcyb.org , sambit@iiserkol.ac.in
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
__author__ = 'Sambit Bikas Pal'


from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app


class pageDB(db.Model):				#Stores page Data
	name=db.StringProperty()
	content=db.TextProperty()
	feed=db.TextProperty()


class MainPage(webapp.RequestHandler):
	def get(self):
	
		#fish out the page from DB and serve it
		storedpages = db.GqlQuery("SELECT * FROM pageDB ORDER BY name")
		for page in storedpages:
				if page.name == "planetiiserk":
					self.response.headers['Content-Type'] = 'text/html'
					self.response.out.write(page.content)
					break


class refreshDB(webapp.RequestHandler):
	def get(self):
		orig_url = "http://abhidg.pagekite.me/planet-iiserk/"
		#try to fetch the fresh page
		try:
			pagecontent = urlfetch.fetch(orig_url)
			pagehtml = pagecontent.content
			# Do some transformation here if needed
			# Replacing my email
			pagehtml = pagehtml.replace('''by Sambit (sambitbikaspal@gmail.com) at''','''by Sambit (sam@botcyb.org) at''')
			contentflag = 1
		except:
			contentflag = 0

		try:
			pagefeed = urlfetch.fetch(orig_url + "atom.xml")
			feedflag = 1
		except:	
			feedflag = 0
			
					
		#if fetch is successful 
		if ((contentflag == 1) and ( feedflag == 1)):
			storedpages = db.GqlQuery("SELECT * FROM pageDB ORDER BY name")
			for page in storedpages:				#fish out old page and delete it
				if page.name == "planetiiserk":
					page.delete()
			page = pageDB()						#create a new pageDB object and store the data
			page.name = "planetiiserk"
			page.content = db.Text(pagehtml, encoding="utf_8")
			page.feed = db.Text(pagefeed.content, encoding="utf_8")
			page.put()
		#if fetch is unsuccessful, then don't do anything with the DB
		else:
			pass

		self.response.headers['Content-Type'] = 'text/plain'
		self.response.out.write('''\n html %s \n feed %s \n'''%(contentflag,feedflag))



class FeedSpew(webapp.RequestHandler):		#serves the cached feeds
	def get(self):
		storedpages = db.GqlQuery("SELECT * FROM pageDB ORDER BY name")
		for page in storedpages:
				if page.name == "planetiiserk":
					self.response.headers['Content-Type'] = 'application/atom+xml'
					self.response.out.write(page.feed)
					break


apps = webapp.WSGIApplication([('/', MainPage),('/atom.xml', FeedSpew),('/refresh', refreshDB)],debug=False)

def main():
	run_wsgi_app(apps)

if __name__ == "__main__":
	main()
